import { login, loginMainByToken } from '@/service/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { setUserInfo, getUserInfo } from '@/utils/userInfo'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  isLogin: false,
  menus: [],
  account: JSON.parse(getUserInfo() || '{}')
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_LOGIN: (state, v) => {
    state.isLogin = v
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      setToken('eyJuYW1lIjoi5ZC05Y+L5ZaEIiwiaWQiOiJlZmExNWYwNi1mNmI5LTQ3MTgtODgwNi03YmFmYTRmNjNiOGMiLCJhY2NvdW50Ijoid3V5b3VzaGFuIn0=')
      setUserInfo({ account: 'robin zhu' })
      resolve()
    })
  },

  // get user info
  getInfo({ commit, state }, data) {
    return login(data).then(res => {
      const roles = []
      const permission = JSON.parse(res.permissionList || '{}')
      if (permission) {
        Object.keys(permission).map(m => {
          if (permission[m] === 1) {
            roles.push(m)
          }
        })
      }
      const name = res.name
      commit('SET_ROLES', roles)
      commit('SET_NAME', name)
      commit('SET_AVATAR', '')
      commit('SET_INTRODUCTION', '')
      commit('SET_LOGIN', true)
      setToken(res.token)
      commit('SET_TOKEN', res.token)
      setUserInfo(res.account)
      return { roles }
    }).catch(ex => {

    })
  },

  // 根据角色获取权限菜单
  getMenuTreeForRole({ commit, state }) {
    return new Promise((resolve, reject) => {
      const token = state.token
      const node = 'fina'
      loginMainByToken({ token, node }).then((response) => {
        const { permissionList } = response
        const roles = []
        const permission = JSON.parse(permissionList || '{}')
        if (permission) {
          Object.keys(permission).map(m => {
            if (permission[m] === 1) {
              roles.push(m)
            }
          })
        }
        if (permissionList) {
          commit('SET_ROLES', roles)
          commit('SET_MENUS', roles) // 存储请求到的数据
          response.token && commit('SET_TOKEN', response.token)
          commit('SET_LOGIN', true)
          resolve(roles)
        } else {
          commit('SET_MENUS', []) // 存储请求到的数据
          commit('SET_ROLES', [])
          resolve([])
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      // dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
